<template>
  <div class="tree-node">
    <div class="node-content">
      <span class="expand-icon" v-if="canAddChildren(node.type, node)" @click.stop="toggleExpand">
        <el-icon><ArrowRight v-if="!node.expanded"/><ArrowDown v-else/></el-icon>
      </span>
      <el-input 
        v-model="node.fieldName"
        v-if="parentNode.type === 'object'"
        placeholder="字段名" 
        class="node-name-input"
        @change="handleFieldNameChange"
      />
      <TypeLabel 
        :type="node.type"
        @click="$emit('showTypeSettings', node)"
      />
      <el-button 
        type="primary" 
        link 
        @click.stop="$emit('addChild', {node,parentNode})" 
        v-if="canAddChildren(node.type, node)"
      >
        <el-icon><Plus /></el-icon>
      </el-button>
      <el-tooltip
        class="box-item"
        effect="dark"
        v-if="node.fieldDesc"
        :content="node.fieldDesc"
        placement="top"
      >
        <el-icon style="margin-inline-end: 5px;"><InfoFilled /></el-icon>
      </el-tooltip>
      <el-button type="danger" link @click.stop="$emit('removeField', {node,parentNode})">
        <el-icon><Delete /></el-icon>
      </el-button>
      <div class="move-buttons" v-if="!isRootNode">
        <el-button 
          type="text" 
          :disabled="isFirstNode" 
          @click.stop="moveNode('up')"
        >
          <el-icon><Top /></el-icon>
        </el-button>
        <el-button 
          type="text" 
          :disabled="isLastNode" 
          @click.stop="moveNode('down')"
        >
          <el-icon><Bottom /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="children" v-if="node.expanded">
      <TreeNode
        v-for="(child, index) in node.APIPOST_ORDERS"
        :key="index"
        :parentNode="node"
        :index="index"
        :list="node.APIPOST_ORDERS"
        :node="node.properties[child]"
        :isExpandable="canAddChildren(node.type, node)"
        @addChild="$emit('addChild', $event)"
        @removeField="$emit('removeField', $event)"
        @showTypeSettings="$emit('showTypeSettings', $event)"
        @move="handleMove"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ArrowRight, ArrowDown, Plus, Delete } from '@element-plus/icons-vue'
import { canAddChildren } from '../utils/nodeUtils'
import TypeLabel from './TypeLabel.vue'

const props = defineProps({
  node: {
    type: Object,
    required: true
  },
  parentNode: {
    type: Object,
    required: true
  },
  list: {
    type: Array
  },
  index: {
    type: Number
  },
})

const emit = defineEmits(['addChild', 'removeField', 'showTypeSettings', 'move'])

const localFieldName = ref('')

// 判断是否是根节点
const isRootNode = computed(() => !props.parentNode || !props.parentNode.APIPOST_ORDERS);

// 判断是否是第一个节点
const isFirstNode = computed(() => props.index === 0);

// 判断是否是最后一个节点
const isLastNode = computed(() => props.index === props.list.length - 1);

// 移动节点
const moveNode = (direction) => {
  const currentIndex = props.index;
  let newIndex;

  if (direction === 'up') {
    newIndex = currentIndex - 1;
  } else if (direction === 'down') {
    newIndex = currentIndex + 1;
  }

  if (newIndex >= 0 && newIndex < props.list.length) {
    // 交换数组中的位置
    const newList = [...props.list];
    [newList[currentIndex], newList[newIndex]] = [newList[newIndex], newList[currentIndex]];

    // 更新父节点的 APIPOST_ORDERS
    props.parentNode.APIPOST_ORDERS = newList;

    // 如果需要同步更新 properties 对象
    const newProperties = {};
    newList.forEach(key => {
      newProperties[key] = props.parentNode.properties[key];
    });
    props.parentNode.properties = newProperties;

    // 触发事件通知父组件
    emit('move', { node: props.node, parentNode: props.parentNode, newIndex });
  }
};

const toggleExpand = () => {
  props.node.expanded = !props.node.expanded
}

const handleFieldNameChange = (value) => {
  if (value.trim()) {
    props.node.fieldName = value.trim()
  }
}

watch(() => props.node.type, (newType) => {
  if (canAddChildren(newType, props.node)) {
    if (!props.node.properties) {
      props.node.properties = {}
    }
    if (!props.node.APIPOST_ORDERS) {
      props.node.APIPOST_ORDERS = []
    }
  }
}, { immediate: true })
</script>

<style scoped>
.tree-node {
  padding: 8px 0;
  display: flex;
  flex-direction: column;
}

.move-buttons {
  display: flex;
  align-items: center;
  margin-left: 5px;
}

.move-buttons .el-button {
  padding: 2px;
  margin: 0;
}

.move-buttons .el-button.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.node-content {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.expand-icon {
  cursor: pointer;
  margin-inline-end: 8px;
}

.node-name-input {
  inline-size: 200px;
  margin-inline-end: 16px;
}

.node-type {
  display: flex;
  align-items: center;
  margin-inline-end: 16px;
}

.type-label {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border: 1px solid;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.type-label:hover {
  opacity: 0.8;
}

.children {
  margin-inline-start: 24px;
  padding-inline-start: 16px;
  border-left: 1px solid #dcdfe6;
}
</style>